package com.xkstream.client.application;

import android.content.Context;
import android.util.DisplayMetrics;
import android.support.multidex.MultiDexApplication;
import com.google.gson.Gson;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.bugly.crashreport.CrashReport;
import com.xkstream.client.ZegoApiManager;
import com.xkstream.client.nim.CustomAttachParser;
import com.xkstream.client.entity.User;
import com.xkstream.client.utils.LogFileUtil;
import com.xkstream.client.utils.PreferenceUtils;
import com.xkstream.client.utils.Utils;
import com.xkstream.client.videothumbloader.cache.DoubleCache;
import com.xkstream.client.videothumbloader.cache.MemoryCache;
import com.xkstream.client.videothumbloader.config.ImageLoaderConfig;
import com.xkstream.client.videothumbloader.core.VideoThumbLoader;
import com.zego.zegoliveroom.ZegoLiveRoom;
import com.zego.zegoliveroom.constants.ZegoAvConfig;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by admin on 2017/3/9.
 */

public class Application extends MultiDexApplication {

    public static Context mContext;

    private static User user;

    private boolean isDownload;

    public static ZegoLiveRoom mZegoLiveRoom;

    // 屏幕参数
    public static int DENSITY;
    public static int WIDTH;
    public static int HEIGHT;

    byte[] signKey = {(byte) 0x0e, (byte) 0x5d, (byte) 0x53, (byte) 0x13, (byte) 0x4e, (byte) 0xf0, (byte) 0x86, (byte) 0xa4, (byte) 0x66,
            (byte) 0x43, (byte) 0x13, (byte) 0xab, (byte) 0xd2, (byte) 0x32, (byte) 0x98, (byte) 0xd0,
            (byte) 0x34, (byte) 0x49, (byte) 0x78, (byte) 0xdd, (byte) 0x22, (byte) 0xe8, (byte) 0xa8, (byte) 0xe2, (byte) 0x85,
            (byte) 0x6d, (byte) 0x26, (byte) 0x9c, (byte) 0x3d, (byte) 0x04, (byte) 0x71, (byte) 0x96};
    long appID = 1196318866;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;

        //初始化云信
        //NIMClient.init(this, null, new SDKOptions());
        if (inMainProcess()) {
          //  NIMClient.getService(MsgService.class).registerCustomAttachmentParser(new CustomAttachParser());
        }
//        initZego();
        initZegoApiManager();
//        ZegoApiManager.getInstance().initSDK();
        initImageLoader(mContext);
        //在这里初始化
        DisplayMetrics dm = this.getResources().getDisplayMetrics();
        WIDTH = dm.widthPixels;
        HEIGHT = dm.heightPixels;
        DENSITY = (int) dm.density;

        if (!LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            LeakCanary.install(this);
        }

        CrashReport.initCrashReport(getApplicationContext(), "f53c881282", false);
        initVideoThumbLoader();
        JPushInterface.setDebugMode(true); // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);

        LogFileUtil.getDefault();

    }

    private void initVideoThumbLoader(){
        ImageLoaderConfig config = new ImageLoaderConfig();
        config.setCache(new DoubleCache(this, new MemoryCache()));
        config.setThreadCount(5);
        VideoThumbLoader.getInstance().init(config);
    }

    public static Application getContext() {
        return (Application) mContext;
    }

    //初始化推流
    private void initZego() {
        // 创建ZegoAVKit对象, 整个项目中创建一次即可，建议封装成单例使用
        mZegoLiveRoom = new ZegoLiveRoom();

// 设置是否开启“测试环境”, true:开启 false:关闭
        mZegoLiveRoom.setTestEnv(false);


// 设置设置调试模式
        mZegoLiveRoom.setVerbose(true);

// ！！！注意：这个Appid和signKey需要从server下发到App，避免在App中存储，防止盗用

// 初始化sdk
        mZegoLiveRoom.initSDK(appID, signKey, mContext);

// 初始化设置级别为"High"
        ZegoAvConfig config = new ZegoAvConfig(ZegoAvConfig.Level.Generic);
        config.setVideoBitrate(600000);
        config.setVideoFPS(15);
        mZegoLiveRoom.setAVConfig(config);
    }

    private void initZegoApiManager() {
        ZegoApiManager.getInstance().setUseVideoFilter(true);
        ZegoApiManager.getInstance().initSDK();
        mZegoLiveRoom = ZegoApiManager.getInstance().getZegoLiveRoom();
    }


    /**
     * 获得状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getStatusHeight(Context context) {
        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    public boolean inMainProcess() {
        String packageName = getPackageName();
        String processName = Utils.getProcessName(this);
        return packageName.equals(processName);
    }

    public static void initImageLoader(Context context) {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO)
                .memoryCache(new WeakMemoryCache())
                .memoryCacheSize(4 * 1024 * 1024).threadPoolSize(3)
                .build();
        ImageLoader.getInstance().init(config);
    }

    public static User getUser() {
        if (user == null) {
            String userStr = PreferenceUtils.getString(PreferenceUtils.USER);
            user = new Gson().fromJson(userStr, User.class);
            return user;
        } else {
            return user;
        }
    }

    public static void setUser(User sUser) {
        user = sUser;
    }

    public void setDownload(boolean b) {
        isDownload = b;
    }

    public boolean isDownload() {
        return isDownload;
    }

}
